﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using umbraco;

namespace TheOutfield.UmbExt.UnVersion
{
    public class UnVersionConfig
    {
        #region Singleton

        private static UnVersionConfig _instance;

        public static UnVersionConfig Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new UnVersionConfig();

                return _instance;
            }
        }

        private UnVersionConfig()
        {
            ConfigEntries = new Dictionary<string, List<UnVersionConfigEntry>>();

            LoadXmlConfig();
        }

        #endregion

        #region Properties

        public Dictionary<string, List<UnVersionConfigEntry>> ConfigEntries { get; set; }

        #endregion

        #region Methods

        private void LoadXmlConfig()
        {
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load(HttpContext.Current.Server.MapPath(GlobalSettings.Path + "/../config/unVersion.config"));

            foreach (XmlNode xmlConfigEntry in xmlConfig.SelectNodes("/unVersionConfig/add"))
            {
                if (xmlConfigEntry.NodeType == XmlNodeType.Element)
                {
                    var configEntry = new UnVersionConfigEntry();

                    if (xmlConfigEntry.Attributes["docTypeAlias"] != null)
                        configEntry.DocTypeAlias = xmlConfigEntry.Attributes["docTypeAlias"].Value;
                    else
                        configEntry.DocTypeAlias = "$_ALL";

                    if (xmlConfigEntry.Attributes["rootXpath"] != null)
                        configEntry.RootXPath = xmlConfigEntry.Attributes["rootXpath"].Value;

                    if (xmlConfigEntry.Attributes["maxDays"] != null)
                        configEntry.MaxDays = Convert.ToInt32(xmlConfigEntry.Attributes["maxDays"].Value);

                    if (xmlConfigEntry.Attributes["maxCount"] != null)
                        configEntry.MaxCount = Convert.ToInt32(xmlConfigEntry.Attributes["maxCount"].Value);

                    if(!ConfigEntries.ContainsKey(configEntry.DocTypeAlias))
                        ConfigEntries.Add(configEntry.DocTypeAlias, new List<UnVersionConfigEntry>());

                    ConfigEntries[configEntry.DocTypeAlias].Add(configEntry);
                }
            }
        }

        #endregion
    }
}